package com.xgkj.diyiketang.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.task.ChongzhiTask;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.OrderInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.BuildOrderTask;
import com.xgkj.diyiketang.util.AlipayUtil;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.diyiketang.weidget.MoneyInputEditText;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;
import com.xgkj.diyiketang.wxapi.WXPayEntryActivity;
import com.xgkj.diyiketang.yizhibo.Constants;

import java.text.DecimalFormat;


public class RechargeActivity extends BaseActivity implements View.OnClickListener {

    private Context mContext;
    private MoneyInputEditText moneyEdit;
    // private RelativeLayout alipayLayout;
    private RelativeLayout weixinpayLayout;
    private String money;
    private int orderTaskId = -1;
    private String channelType;
    private String payChannel;
    private static final String ALIPAY_TYPE = "1";
    private static final String WEIXINPAY_TYPE = "0";
    private String orderTitle = "第一课堂";
    private String orderBody = "第一课堂";
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private WeixinReceive mWeiXinReceive;
    private ProgressDialog mProgress;
    private ImageView mWeixin_check;
    private ImageView mAli_check;
    private Button zhifu_btn;
    private TextView moneyText, money_tv;
    private String moneyChanged;
    private String yaoqingma = "";
    private int paytaskid = -1;
    private String pay_money;
    private String orderNo;
    private String type;
    private String identity;
    private String quotaId;
    private String jibie = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recharge);
        mContext = this;
        msgApi.registerApp(ProtocolConst.APP_ID);
        initView();
    }

    private void initView() {
        money_tv = (TextView) findViewById(R.id.money_tv);
        moneyEdit = (MoneyInputEditText) findViewById(R.id.money_amount);
        moneyText = (TextView) findViewById(R.id.money_text);
        // alipayLayout = (RelativeLayout) findViewById(R.id.alipay_layout);
        weixinpayLayout = (RelativeLayout) findViewById(R.id.weixinpay_layout);
        // alipayLayout.setOnClickListener(this);
        weixinpayLayout.setOnClickListener(this);
        ((TextView) findViewById(R.id.back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mWeixin_check = (ImageView) findViewById(R.id.weixin_check);
        mAli_check = (ImageView) findViewById(R.id.zhifubao_check);
        zhifu_btn = (Button) findViewById(R.id.zhifu_btn);
        zhifu_btn.setOnClickListener(this);
        mWeixin_check.setVisibility(View.VISIBLE);
        mAli_check.setVisibility(View.GONE);
        channelType = WEIXINPAY_TYPE;
        if (getIntent().getExtras() != null) {

//        }
//        if (!TextUtils.isEmpty(getIntent().toString())) {
            if (getIntent().getExtras().getString("type") != null) {
                type = getIntent().getExtras().getString("type");
                if (type.equals("zhuanyun")) {
                    quotaId = "3d9513eb1b674af98de226b315765e3f";
                } else if (type.equals("parent")) {
                    quotaId = "2737f7a418bf41c998728e6a0f9f253d";
                }else if (type.equals("guoxuexueyuan")){
                    money_tv.setText("￥ 2998");
                    moneyText.setText("￥ 2998");
                    moneyEdit.setVisibility(View.GONE);
                    money = "2998";
//                    money = "0.01";
                }
                TextView title = (TextView) findViewById(R.id.chongzhi_title);
//                if (type.equals("zhuanyunxueyuan")) {
                if (getIntent().getExtras().getString("jibie")!=null){
                    jibie = getIntent().getExtras().getString("jibie");
                }
                if (jibie.equals("yuanzhang")) {
                    identity = "0";
                    money_tv.setText("￥ 10000");
                    moneyText.setText("￥ 10000");
                    moneyEdit.setVisibility(View.GONE);
                    money = "10000";
                } else if (jibie.equals("zhuren")) {
                    identity = "1";
                    money_tv.setText("￥ 5000");
                    moneyText.setText("￥ 5000");
                    moneyEdit.setVisibility(View.GONE);
                    money = "5000";
                } else if (jibie.equals("daoshi")) {
                    identity = "2";
                    money_tv.setText("￥ 1000");
                    moneyText.setText("￥ 1000");
                    moneyEdit.setVisibility(View.GONE);
                    money = "1000";
                } else if (jibie.equals("xueyuan")) {
                    identity = "3";
                    money_tv.setText("￥ 399");
                    moneyText.setText("￥ 399");
                    moneyEdit.setVisibility(View.GONE);
                    money = "399";
                }
                title.setText("购买");
                if (!TextUtils.isEmpty(getIntent().getExtras().getString("yaoqingma"))) {
                    yaoqingma = getIntent().getExtras().getString("yaoqingma");
                } else {
                    yaoqingma = "";
                }
//                }
            }
        }

        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                moneyChanged = moneyEdit.getText().toString();
                moneyText.setText("￥" + moneyChanged);
            }
        });


    }

    private void zhifu() {
//        money = "0.01";
//        quotaId = "3d9513eb1b674af98de226b315765e3f";
        if (identity == null) {
            ToastUtil.showMessage(this, "参数有误，请退出重新登录");
            return;
        }
        if (money == null) {
            ToastUtil.showMessage(this, "参数有误，请退出重新登录");
            return;
        }
        BuildOrderTask orderTask = new BuildOrderTask(null, "4", money, yaoqingma, null, "0", identity, quotaId, null, null, null);
        orderTask.addListener(buildOrderListener);
        paytaskid = getEatShowApp().getTaskManager().addTask(orderTask);
    }

    private void getOrder() {
        ChongzhiTask task = new ChongzhiTask(money);
//        BuildOrderTask task = new BuildOrderTask("",  "1", money, channelType);
        task.addListener(buildOrderListener);
        orderTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private TaskEventListener buildOrderListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (orderTaskId == taskId) {
                orderTaskId = -1;
                OrderInfo orderInfo = null;
                if (data != null) {
                    orderInfo = (OrderInfo) data;
                }
                orderNo = orderInfo.getOrderNo();
                payChannel = orderInfo.getPayChannel();
                doWeixinPay();
            } else if (paytaskid == taskId) {
                if (data != null) {
                    OrderInfo orderInfo = (OrderInfo) data;
                    dismissDialog();
                    if (orderInfo != null) {
                        orderNo = orderInfo.getOrderNo();
                        doWeixinPay();
                    }
                }

            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            orderTaskId = -1;
            paytaskid = -1;
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    private void doAliPay() {
        AlipayUtil.doAlipay(alipayHandler, RechargeActivity.this, orderNo, orderTitle, orderBody, money);
    }

    private void doWeixinPay() {
        if (!msgApi.isWXAppSupportAPI() || !msgApi.isWXAppInstalled()) {
            ToastUtil.showMessage(mContext, R.string.need_weixin_app);
            return;
        }

        if (mWeiXinReceive == null) {
            mWeiXinReceive = new WeixinReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXPayEntryActivity.WEIXIN_PAY_SUCCESS_ACTION);
            registerReceiver(mWeiXinReceive, filter);
        }
        new WeiXinPay(msgApi, RechargeActivity.this, orderNo, orderBody, money);

//        finish();
    }

    private Handler alipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private void showProgress() {
        if (mProgress == null) {
            mProgress = DialogUtil.showProgressDialog(mContext, getString(R.string.get_pageinfo_loading), new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    mProgress = null;
                }
            });
        }
    }

    private void dismissDialog() {
        if (mProgress != null && mProgress.isShowing()) {
            mProgress.dismiss();
            mProgress = null;
        }
    }


    @Override
    public void onClick(View v) {
//        if (checkInput()) {
        switch (v.getId()) {
            case R.id.alipay_layout:
                mAli_check.setVisibility(View.VISIBLE);
                mWeixin_check.setVisibility(View.GONE);
                channelType = ALIPAY_TYPE;
                //getOrder();

                break;
            case R.id.weixinpay_layout:
                mWeixin_check.setVisibility(View.VISIBLE);
                mAli_check.setVisibility(View.GONE);
                channelType = WEIXINPAY_TYPE;
//                    getOrder();
                break;
            case R.id.zhifu_btn:
                if (type != null && type.equals("zhuanyun") && checkIsPay()) {
                    if (!TextUtils.isEmpty(money)) {
                        zhifu();
                    } else {
                        ToastUtil.showMessage(this, "钱数为空");
                    }
                } else if (type != null && type.equals("parent") && checkIsPay()) {
                    if (!TextUtils.isEmpty(money)) {
                        zhifu();
                    } else {
                        ToastUtil.showMessage(this, "钱数为空");
                    }
                } else if (type != null && type.equals("guoxuexueyuan") && checkIsPay()) {
                    if (!TextUtils.isEmpty(money)) {
                        if (money == null) {
                            ToastUtil.showMessage(this, "参数有误，请退出重新登录");
                            return;
                        }
                        BuildOrderTask orderTask = new BuildOrderTask(null, "5", money, yaoqingma, null, "0", "", "", null, null, null);
                        orderTask.addListener(buildOrderListener);
                        paytaskid = getEatShowApp().getTaskManager().addTask(orderTask);
                    } else {
                        ToastUtil.showMessage(this, "钱数为空");
                    }
                }else if (checkIsPay() && checkInput()) {
                    getOrder();
                }

                break;
            default:
                break;
        }
//        }
    }

    private boolean checkInput() {
        money = moneyEdit.getText().toString();
        double money_d = 0;
        DecimalFormat format = new DecimalFormat("0.00");
        if (money != null) {
            try {
                money_d = Double.parseDouble(money);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (money_d <= 0) {
                Toast.makeText(mContext, R.string.money_not_null, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    class WeixinReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isSuccess = intent.getBooleanExtra(ProtocolConst.WEIXINPAY_SUCCESS, false);
            if (isSuccess) {
                finish();
            } else {

            }

            if (mWeiXinReceive != null) {
                unregisterReceiver(mWeiXinReceive);
                mWeiXinReceive = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWeiXinReceive != null) {
            unregisterReceiver(mWeiXinReceive);
            mWeiXinReceive = null;
        }
    }


    private boolean checkIsPay() {

        if (TextUtils.isEmpty(channelType)) {
            Toast.makeText(mContext, R.string.no_check_pay, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }
}
